<?php

namespace app\common\services;

use app\admin\model\Admin as uModel;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\Paginator;
use GuzzleHttp\Client;
use app\admin\model\spider\Spider as spiderModel;
use app\admin\model\spider\Task as taskModel;
use app\admin\model\spider\SpiderPrices as spiderPricesModel;
use app\admin\model\spider\FailImages as spiderFailImagesModel;

/**
 * 任务
 */
class Task
{
    /**
     * 获取单条任务数据
     * @param $where
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getTaskRow($where)
    {
        return taskModel::where($where)->with(['platform'])->find();
    }
    /**
     * 获取单条商品数据
     * @param $where
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getSpiderRow($where)
    {
        return spiderModel::where($where)->find();
    }


    public static function spider($params)
    {
        if (empty($params['get_url'])) {
            return false;
        }

        //检测单链接还是多链接
        if (!isset($params['shop_uniqid'])) {
            $taskRow = self::getTaskRow(['task.id' => $params['task_id']]);
            if (empty($taskRow)) {
                return false;
            }
            $taskRow->status = 2;
            $taskRow->save();
        }

        //抓取页面数据操作
        $data = \spider\Spider::spider($params);

        try {
            //更新商品信息
            if (!empty($data['shopInfo'])) {
                if (!isset($data['shopInfo']['name'])) return false;

                $spiderRow = self::getSpiderRow(['shop_uniqid' => $data['shopInfo']['shop_uniqid']]);
                $spiderRow->page_title = $data['shopInfo']['page_title']; //title标签
                $spiderRow->meta_description = $data['shopInfo']['meta_description']; //meta的描述
                $spiderRow->store_url = $data['shopInfo']['store_url']; //店铺地址
                $spiderRow->shop_description = $data['shopInfo']['shop_description']; //商品描述
                $spiderRow->save();

                //保存价格数据
                (new spiderPricesModel)->allowField(true)->saveAll($data['list']);
            } else {
                if (!empty($data)) {
                    //修改状态及记录抓取耗时
                    $taskRow->status = 3;
                    $taskRow->shop_count = $data['count'];
                    $taskRow->use_time = time() - $taskRow->updatetime;

                    //保存数据
                    (new spiderModel)->allowField(true)->saveAll($data['list']);
                } else {
                    $taskRow->status = 4;
                }
                $taskRow->save();
            }

        } catch (Exception $exception) {
            halt($exception->getMessage());
        }

        return true;
    }


    public static function imagesFailRecord($params)
    {
        $data = [
            'shop_uniqid' => $params['shop_uniqid'],
            'url' => $params['url'],
            'local_img_url' => $params['local_img_url'],
        ];
        (new spiderFailImagesModel)->allowField(true)->save($data);
    }


    /**
     * 抓取单个亚马逊商品
     * @param $url string 商品URL
     * @return
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private static function getAmazonRow(string $url)
    {
        // 创建Guzzle客户端
        $client = new Client([
            'verify' => false, // 禁用SSL验证
        ]);

        try {
            // 发送HTTP请求
            $response = $client->request('GET', $url, [
                'headers' => [
                    'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
                    'Accept-Encoding' => 'gzip, deflate, br',
                    'Accept-Language' => 'en-US,en;q=0.9',
                    'Referer' => 'https://www.amazon.com/',
                ],
            ]);

            // 获取HTML内容
            $html = $response->getBody()->getContents();

            file_put_contents(ROOT_PATH."/html.html", $html);
//            $html = file_get_contents(ROOT_PATH."/html.html");

            // 使用正则表达式提取商品标题
            $titlePattern = '/<span\s+id="productTitle"[^>]*>(.*?)<\/span>/s';
            preg_match($titlePattern, $html, $titleMatches);
            $title = isset($titleMatches[1]) ? trim($titleMatches[1]) : 'Title not found';
            echo "Title: " . $title . "\n";

            // 使用正则表达式提取商品价格
            $pricePatterns = [
                '/<span\s+class="a-price\s+a-text-price\s+a-size-medium"[^>]*>\s*<span[^>]*>(.*?)<\/span>/s', // 常规价格
                '/<span\s+class="a-price\s+aok-align-center"[^>]*>\s*<span[^>]*>(.*?)<\/span>/s', // 促销价格
                '/<span\s+id="priceblock_ourprice"[^>]*>(.*?)<\/span>/s', // 旧版价格标签
                '/<span\s+id="priceblock_dealprice"[^>]*>(.*?)<\/span>/s', // 特价标签
            ];

            $price = 'Price not found';
            foreach ($pricePatterns as $pattern) {
                if (preg_match($pattern, $html, $priceMatches)) {
                    $price = trim($priceMatches[1]);
                    break;
                }
            }
            $price = explode("$", $price);
            if (isset($price[1])) {
                $price = $price[1];
            }
            // 输出结果
            echo "Price: " . $price . "\n";

            // 使用正则表达式提取商品图片URL
//            $imagePatterns = [
//                // 匹配主图（通常位于 id="landingImage" 的 img 标签中）
//                '/<img[^>]+src="([^"]+)"[^>]+data-a-image-name="landingImage"/s',
//                // 匹配其他商品图片（通常位于 class="a-dynamic-image" 的 img 标签中）
//                '/<img\s+[^>]*class="a-dynamic-image"[^>]*src="([^"]+)"[^>]*>/i',
//                // 匹配缩略图（通常位于 data-a-dynamic-image 的 img 标签中）
//                '/<img\s+[^>]*data-a-dynamic-image="[^"]*"[^>]*src="([^"]+)"[^>]*>/i',
//            ];
//            $productImages = [];
//            foreach ($imagePatterns as $pattern) {
//                if (preg_match_all($pattern, $html, $matches)) {
//                    foreach ($matches[1] as $imageUrl) {
//                        // 去重并添加到结果中
//                        if (!in_array($imageUrl, $productImages)) {
//                            $productImages[] = $imageUrl;
//                        }
//                    }
//                }
//            }
            $pattern = '/<img[^>]+(?:data-old-hires|src)=["\'](https:\/\/m\.media-amazon\.com\/images\/I\/[^"\']+\.(?:jpg|png|jpeg))["\']/i';
            preg_match_all($pattern, $html, $matches);
            // 提取所有图片 URL
            $productImages = array_unique($matches[1]); // 去重

            $productImages = implode(",", $productImages);
//            dump($productImages);

            return [
                'title' => $title,
                'price' => $price,
                'img' => $productImages,
            ];

        } catch (Exception $e) {
            echo "Error: " . $e->getMessage();
        }
    }


}